import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

# 定义目标函数
def target_function(x):
    return 1 / np.cosh(x)

# 定义有理函数形式
def rational_function(x, a, b, c, d):
    return (a * x + b) / (x**2 + c * x + d)

# 定义拟合区间和采样点
x_data = np.linspace(1, 5, 500)
y_data = target_function(x_data)

# 初始参数猜测
initial_guess = [1, 1, 1, 1]

# 拟合参数
params, _ = curve_fit(rational_function, x_data, y_data, p0=initial_guess)

# 提取拟合参数
a, b, c, d = params

# 生成拟合结果
y_fit = rational_function(x_data, a, b, c, d)

# 可视化结果
plt.figure(figsize=(8, 5))
plt.plot(x_data, y_data, label="Target: 1/cosh(x)", linewidth=2)
plt.plot(x_data, y_fit, label=f"Rational Approx: ({a:.2f}x + {b:.2f}) / (x^2 + {c:.2f}x + {d:.2f})", linestyle="--")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.legend()
plt.grid()
plt.title("Rational Approximation of 1/cosh(x)")
plt.show()